import Vue from 'vue'
import App from './App.vue'
import router, {resetRouter} from './router'
import store from './store'
import Antd from 'ant-design-vue';
import 'ant-design-vue/dist/antd.css';
import './styles/comment.less'
import './styles/init-ant-design.less'
import {getAPIs} from './apis/getAPIClass'
Vue.use(Antd);

Vue.config.productionTip = false

Vue.prototype.$getAPIs = getAPIs;

// index.js
import microApp from '@micro-zoe/micro-app'
import {StorageUtil} from "@/utils/StorageUtil";

microApp.start()

router.beforeEach((to, from, next) => {
  // 判断是否已经登录，没有登录直接跳到首页
  const isLogin = StorageUtil.getItem('TOKEN')
  if (!isLogin && to.path != '/login') return next('/login');
  console.log("路由跳转至：" , to)
  if (!['/login', '/'].includes(to.path)) {

  }
  store.commit('UPDATE_ACTIVE_MEUN', to.path)
  console.log(store.getters.accessedRoutes, "store.getters.accessedRoutes")
  // if (to.path == '/login') {
  //   StorageUtil.remove('TOKEN');
  //   next();
  // }
  if (isLogin && (to.path == '/login' || to.path == '/')) {
    if (store.getters.accessedRoutes.length == 0) {

    }
    next('/layout/home');
  }
  // 如果是从登录页面跳转到home页面 或者 已经登录了但是动态加载页面数据为空，则去加载动态路由
  // if ((from.path == '/login' && to.path == '/layout/home') || (isLogin && store.getters.accessedRoutes.length == 0)) {
  // if (((from.path == '/login' || from.path == '/') && to.path == '/layout/home') ) {
  if (((from.path == '/login' || from.path == '/') && isLogin) ) {
    resetRouter();
    store.dispatch('GenerateRoutes', {  }).then(accessRoutes => {

      // 测试 默认静态页面
      // store.dispatch('permission/generateRoutes', { roles }).then(accessRoutes => {
      // 根据roles权限生成可访问的路由表
      console.log(accessRoutes)
      router.addRoutes(accessRoutes) // 动态添加可访问路由表
      console.log("动态加载了路由");
      next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
    })

  }
  next();
})

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
